/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.editor.view;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;

import javax.swing.JEditorPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultCaret;
import javax.swing.text.JTextComponent;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.Position;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;

import offset.nodes.client.editor.Editor;
import offset.nodes.client.editor.controller.TableActions;
import offset.nodes.client.editor.model.DocumentContext;
import offset.nodes.client.editor.model.TableModel;

/**
 *
 * @author Walter Lütgenau
 * @version
 */
public class EditorCaret extends DefaultCaret {

    Editor editor;
    private static final int DRAG_DISTANCE = 10;
    // --- drag ------------------------------------------
    boolean inTableDrag = false;
    int dragStartPos = -1;
    int dragStartX = -1;
    int dragStartWidth = -1;
    private static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
    private static final Cursor textCursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);
    BasicStroke dashStroke = new BasicStroke(1.f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.f,
            new float[]{1.f, 1.f}, 0.f);
    MutableAttributeSet input;
    /**
     * This is used by viewToModel to avoid allocating a new array each time.
     */
    protected Position.Bias[] bias = new Position.Bias[1];
    protected int x = -1;
    JPopupMenu popupMenu = null;

    /**
     * Creates new Editor caret with a given popup menu
     *
     * @param popupMenu
     */
    public EditorCaret(JPopupMenu popupMenu, Editor editor) {
        this.editor = editor;
        if (popupMenu == null) {
            this.popupMenu = buildPopupMenu();
        } else {
            this.popupMenu = popupMenu;
        }
        setBlinkRate(500);
        setVisible(true);
    }

    protected void positionCaret(MouseEvent e) {
        super.positionCaret(e);
        editor.fireUserCaretEvent();
        // adjustment may have spoilt the position, so position again
        //super.positionCaret(e);
    }

    protected void moveCaret(MouseEvent e) {
        super.moveCaret(e);
        editor.fireUserCaretEvent();
        // adjustment may have spoilt the position, so position again
        //super.moveCaret(e);
    }
    // MouseListener methods    

    @Override
    public void mouseReleased(MouseEvent e) {
        JTextComponent c = getComponent();
        if (c != null) {
            // Show popup menu for right click
            if (SwingUtilities.isRightMouseButton(e)) {
                popupMenu.show(c, e.getX(), e.getY());
                return;
            }
        }

        if (!inTableDrag) {
            return;
        }

        JEditorPane editor = (JEditorPane) e.getSource();

        Rectangle editorRectangle = editor.getVisibleRect();

        Graphics2D g = (Graphics2D) e.getComponent().getGraphics();
        Stroke currentStroke = g.getStroke();
        g.setStroke(dashStroke);
        g.setXORMode(Color.white);

        if (x >= 0) {
            g.drawLine(x, editorRectangle.y, x, editorRectangle.y + editorRectangle.height);
        }

        g.setPaintMode();
        g.setStroke(currentStroke);

        try {
            updateCells(e);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        inTableDrag = false;

        x = -1;
    }

    protected void updateCells(MouseEvent e) throws Exception {
        TableActions.UpdateColumnWidthsAction action = new TableActions.UpdateColumnWidthsAction(dragStartPos, dragStartX - dragStartWidth, (int) dragStartX, e.getX(), editor);
        action.actionPerformed(new ActionEvent(e.getSource(), 0, null));
    }

    public void mouseDragged(MouseEvent e) {
        if (!inTableDrag) {
            super.mouseDragged(e);
            return;
        }

        JEditorPane editor = (JEditorPane) e.getSource();

        Rectangle editorRectangle = editor.getVisibleRect();

        Graphics2D g = (Graphics2D) e.getComponent().getGraphics();
        Stroke currentStroke = g.getStroke();
        g.setStroke(dashStroke);
        g.setXORMode(Color.white);

        if (x >= 0) {
            g.drawLine(x, editorRectangle.y, x, editorRectangle.y + editorRectangle.height);
        }
        g.drawLine(e.getX(), editorRectangle.y, e.getX(), editorRectangle.y + editorRectangle.height);

        g.setPaintMode();
        g.setStroke(currentStroke);

        x = e.getX();
    }

    // track the moving of the mouse.
    public void mouseMoved(MouseEvent e) {
        JEditorPane editor = (JEditorPane) e.getSource();

        Point pt = new Point(e.getX(), e.getY());
        int pos = editor.getUI().viewToModel(editor, pt, bias);
        if (bias[0] == Position.Bias.Backward && pos > 0) {
            pos--;
        }

        if (pos < 0) {
            return;
        }

        HTMLDocument doc = (HTMLDocument) editor.getDocument();

        if (!getModel(e).isTable(pos) || getModel(e).getTableWidthType(pos) == TableModel.COLUMN_WIDTH_TYPE_VARIABLE) {
            return;
        }

        if (atColumnBorder(e, pos, pt)) {
            if (editor.getCursor().getType() != Cursor.E_RESIZE_CURSOR) {
                editor.setCursor(resizeCursor);
            }
            inTableDrag = true; // it is possible, that a table drag is starting from here
            dragStartPos = pos;
            dragStartX = pt.x;
            dragStartWidth = getModel(e).getColumnWidth(pos, getComponent().getWidth());
        } else {
            if (editor.getCursor().getType() != Cursor.TEXT_CURSOR) {
                editor.setCursor(textCursor);
            }
            inTableDrag = false;
        }
    }

    protected boolean atColumnBorder(MouseEvent e, int pos, Point pt) {
        try {
            TableModel model = getModel(e);
            if (model.isLastCellOfRow(pos) && model.getTableWidthValue(pos).equals("100%")) {
                return false;
            }

            int columnStart = model.getStartOfCell(pos);
            Rectangle r = null;
            if (model.getTableWidthType(pos) == TableModel.COLUMN_WIDTH_TYPE_FIXED || model.isLastCellOfRow(pos)) {
                //r = getComponent().getUI().modelToView( getComponent(), columnStart );
                r = model.getElementShape(model.getAncestor(pos, HTML.Tag.TD)).getBounds();
                r.x += getModel(e).getColumnWidth(pos, getComponent().getWidth());
            } else {
                int nextColumnStart = model.getStartOfNextCell(pos);
                //r = getComponent().getUI().modelToView( getComponent(), nextColumnStart );
                r = model.getElementShape(model.getAncestor(nextColumnStart, HTML.Tag.TD)).getBounds();
            }

            if (Math.abs(r.x - pt.x) < DRAG_DISTANCE || Math.abs(r.x + r.width - pt.x) < DRAG_DISTANCE) {
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return false;
    }

    // scroll to caret, yes or no?
    boolean adjustVisibility = true;

    public boolean isAdjustVisibility() {
        return adjustVisibility;
    }

    public void setAdjustVisibility(boolean adjustVisibility) {
        this.adjustVisibility = adjustVisibility;
    }
    
    protected void adjustVisibility(Rectangle nloc) {
        if (adjustVisibility)
            super.adjustVisibility(nloc);
    }

    protected JPopupMenu buildPopupMenu() {
        JPopupMenu pm = new JPopupMenu();
        return pm;
    }

    protected TableModel getModel(MouseEvent e) {
        JEditorPane pane = (JEditorPane) e.getSource();
        return new TableModel(new DocumentContext(pane));
    }

    public JPopupMenu getPopupMenu() {
        return popupMenu;
    }

    public void setPopupMenu(JPopupMenu popupMenu) {
        this.popupMenu = popupMenu;
    }
}
